package com.eneat.smartrule.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eneat.smartrule.dto.request.RuleReq;
import com.eneat.smartrule.dto.response.PageResponse;
import com.eneat.smartrule.dto.response.RuleRes;
import com.eneat.smartrule.mapper.RuleMapper;
import com.eneat.smartrule.model.Rule;
import com.eneat.smartrule.repository.RuleConditionRepo;
import com.eneat.smartrule.repository.RuleRepo;
import com.google.common.base.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class RuleRepoImpl implements RuleRepo {

    @Autowired
    private RuleMapper mapper;
    @Autowired
    private RuleConditionRepo ruleConditionRepo;
    @Override
    public PageResponse<RuleRes> searchRules(RuleReq ruleReq) {
        LambdaQueryWrapper<Rule> queryWrapper = new LambdaQueryWrapper<>();
        // 按规则名称模糊查询
        if (!Strings.isNullOrEmpty(ruleReq.getName())) {
            queryWrapper.like(Rule::getName, ruleReq.getName());
        }
        // 按规则状态查询（0: 禁用, 1: 启用）
        if (ruleReq.getStatus() != null) {
            queryWrapper.eq(Rule::getStatus, ruleReq.getStatus());
        }
        // 按创建时间范围查询
        if (ruleReq.getCreateTimeStart() != null && ruleReq.getCreateTimeEnd() != null) {
            queryWrapper.between(Rule::getCreateTime, ruleReq.getCreateTimeStart(), ruleReq.getCreateTimeEnd());
        } else if (ruleReq.getCreateTimeStart() != null) {
            queryWrapper.ge(Rule::getCreateTime, ruleReq.getCreateTimeStart()); // 大于等于开始时间
        } else if (ruleReq.getCreateTimeEnd() != null) {
            queryWrapper.le(Rule::getCreateTime, ruleReq.getCreateTimeEnd()); // 小于等于结束时间
        }
        // 分页参数
        Page<Rule> page = new Page<>(ruleReq.getPageNum(), ruleReq.getPageSize());
        // 执行分页查询
        Page<Rule> resultPage = mapper.selectPage(page, queryWrapper);
        List<Rule> records = resultPage.getRecords();
        List<RuleRes> ruleResList = new ArrayList<>();
        BeanUtils.copyProperties(records, ruleResList);
        records.forEach(rule -> rule.setRuleConditions(ruleConditionRepo.findByRuleId(rule.getId())));
        return PageResponse.of(
                ruleResList,
                ruleReq.getPageNum(),
                ruleReq.getPageSize(),
                resultPage.getTotal()
        );
    }
}
